
#include "pincfg.h"
#include "code_verify.h"
#include "dataproc.h"
#include "sys_init.h"
#include "common.h"

//密码空间2KB
#define FLASH_Unlock HAL_FLASH_Unlock
#define FLASH_Lock HAL_FLASH_Lock
//#define FLASH_ProgramWord FLASH_ProgramWord
#define FLASH_Erase FLASH_ErasePage

OBJ_USED const uint32_t verify_flag[2] = {UINT32_MAX, UINT32_MAX}; 
void cvf_verify_check(void);

/*****************************************************************************/ /*!
* @brief   jiami.   实际代码大约200-300字节，开优化
*					可将代码对齐在擦除扇区边界
*					直接擦除加密后直接擦除即可，无需填充操作，0xFFFF执行和NOP同
* @param   none		
* @return  none
* @ Pass/ Fail criteria: none
*****************************************************************************/
void cvf_handle(void)
{
	int group, reg_flag;
    cvf_check_alloc();
	
	// check
	reg_flag = code_set_lb(reg_flag, ((uu32)(verify_flag) >> 0) & 0xFF);
	reg_flag = code_set_hb(reg_flag, ((uu32)(verify_flag) >> 8) & 0xFF);
	reg_flag = code_set_ub(reg_flag, ((uu32)(verify_flag) >> 16) & 0xFF);
	reg_flag = code_set_mb(reg_flag, ((uu32)(verify_flag) >> 24) & 0xFF);
	
	if(inpw(reg_flag) != UINT32_MAX)
	{
		dbg_puts("enc book has been created, skip!\n");
		return;
	}
	
	// enc opt
	cvf_enc_rom_addr_make(0, 0);
	
    FLASH_Unlock();		//解锁flash
	
	FLASH->SR |= FLASH_SR_PGAERR | FLASH_SR_PGPERR | FLASH_SR_PGSERR;
	
    //FLASH_Erase(cvf.addr);
	FLASH_Erase_Sector(FLASH_SECTOR_1, FLASH_VOLTAGE_RANGE_3);
	
	for(group=0; group < CFV_CODE_LEN/8; group++)
	{
		cvf_enc_gen(group);
		
		cvf_enc_rom_addr_make(group, 0);
		
		HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, cvf.addr + 0, cvf.out[0]);
		HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, cvf.addr + 4, cvf.out[1]);
	}
    
	cvf_free();
	
	//dbg_u8_print("jiami: \n", (void *)CVF_ENC_ADDR, CFV_CODE_LEN, 32);
	
	// flag
	HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, reg_flag + 0, 0x13266231);
	HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, reg_flag + 4, ~0x13266231);
	
    FLASH_Lock();

	dbg_puts("enc comp!\n");
	dbg_print("enc flag : %08X, %08X\n", inpw(reg_flag), inpw(reg_flag + 4));
}


int cvf_gen(int argc, char *argv[])
{
	cvf_handle();
	cvf_verify_check();
	
	return 0;
}
DBG_FUN_EXPORT(cvf_gen);
